package glpm

import (
	"context"
	"fmt"
	"strings"
)

// ApkManager APK包管理器实现
type ApkManager struct {
	*BaseManager
}

// NewApkManager 创建APK包管理器
func NewApkManager(config *ManagerConfig) *ApkManager {
	base := NewBaseManager("apk", config)
	return &ApkManager{
		BaseManager: base,
	}
}

// Install 安装包
func (am *ApkManager) Install(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要安装的包名")
	}
	
	args := []string{"add", "--no-cache"}
	args = append(args, packages...)
	
	_, err := am.executeCommand(ctx, args...)
	return err
}

// Remove 移除包
func (am *ApkManager) Remove(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要移除的包名")
	}
	
	args := []string{"del", "--no-cache"}
	args = append(args, packages...)
	
	_, err := am.executeCommand(ctx, args...)
	return err
}

// Update 更新包列表
func (am *ApkManager) Update(ctx context.Context) error {
	_, err := am.executeCommand(ctx, "update")
	return err
}

// Upgrade 升级包
func (am *ApkManager) Upgrade(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		// 系统升级
		_, err := am.executeCommand(ctx, "upgrade", "--no-cache")
		return err
	}
	
	// 升级特定包
	args := []string{"add", "--upgrade", "--no-cache"}
	args = append(args, packages...)
	
	_, err := am.executeCommand(ctx, args...)
	return err
}

// Search 搜索包
func (am *ApkManager) Search(ctx context.Context, pattern string) ([]PackageInfo, error) {
	output, err := am.executeCommand(ctx, "search", pattern)
	if err != nil {
		return nil, err
	}
	
	return am.parseSearchOutput(output)
}

// Info 获取包信息
func (am *ApkManager) Info(ctx context.Context, packageName string) (*PackageInfo, error) {
	output, err := am.executeCommand(ctx, "info", packageName)
	if err != nil {
		return nil, err
	}
	
	return am.parseInfoOutput(output)
}

// ListInstalled 列出已安装的包
func (am *ApkManager) ListInstalled(ctx context.Context) ([]PackageInfo, error) {
	output, err := am.executeCommand(ctx, "info", "--installed")
	if err != nil {
		return nil, err
	}
	
	return am.parseListOutput(output)
}

// IsInstalled 检查指定包是否已安装
func (am *ApkManager) IsInstalled(ctx context.Context, packageName string) (bool, error) {
	packages, err := am.ListInstalled(ctx)
	if err != nil {
		return false, err
	}
	
	for _, pkg := range packages {
		if pkg.Name == packageName {
			return true, nil
		}
	}
	
	return false, nil
}

// parseSearchOutput 解析搜索输出
func (am *ApkManager) parseSearchOutput(output string) ([]PackageInfo, error) {
	var packages []PackageInfo
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "fetch") {
			continue
		}
		
		// 解析格式: package-version description
		parts := strings.Fields(line)
		if len(parts) >= 2 {
			nameVersion := strings.Split(parts[0], "-")
			pkgName := strings.Join(nameVersion[:len(nameVersion)-1], "-")
			
			packages = append(packages, PackageInfo{
				Name:        pkgName,
				Version:     nameVersion[len(nameVersion)-1],
				Description: strings.Join(parts[1:], " "),
			})
		}
	}
	
	return packages, nil
}

// parseInfoOutput 解析包信息输出
func (am *ApkManager) parseInfoOutput(output string) (*PackageInfo, error) {
	info := &PackageInfo{}
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		
		if strings.HasPrefix(line, "package:") {
			info.Name = strings.TrimSpace(strings.TrimPrefix(line, "package:"))
		} else if strings.HasPrefix(line, "version:") {
			info.Version = strings.TrimSpace(strings.TrimPrefix(line, "version:"))
		} else if strings.HasPrefix(line, "architecture:") {
			info.Architecture = strings.TrimSpace(strings.TrimPrefix(line, "architecture:"))
		} else if strings.HasPrefix(line, "description:") {
			info.Description = strings.TrimSpace(strings.TrimPrefix(line, "description:"))
		}
	}
	
	return info, nil
}

// parseListOutput 解析列表输出
func (am *ApkManager) parseListOutput(output string) ([]PackageInfo, error) {
	var packages []PackageInfo
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "fetch") {
			continue
		}
		
		// 解析格式: package-version description
		parts := strings.Fields(line)
		if len(parts) >= 2 {
			nameVersion := strings.Split(parts[0], "-")
			pkgName := strings.Join(nameVersion[:len(nameVersion)-1], "-")
			
			packages = append(packages, PackageInfo{
				Name:    pkgName,
				Version: nameVersion[len(nameVersion)-1],
				Status:  "installed",
			})
		}
	}
	
	return packages, nil
}